const express = require('express');
const co = require('co');
const rongCloud = require('rongcloud-sdk');
const Config = require('config');
const Session = require('../util/session');
const Utility = require('../util/util').Utility;
const APIResult = require('../util/util').APIResult;
const auth = require('../util/auth');
const TeamService = require('../services/team-service');
const UserService = require('../services/user-services');

const modles = require('../models');
var User = modles.User;
const OnlineStatus = modles.OnlineStatus;
var logger = require('flogger').getLogger();

// const MAX_GROUP_MEMBER_COUNT = 500;
// const NICKNAME_MIN_LENGTH = 1;
// const NICKNAME_MAX_LENGTH = 32;
// const PORTRAIT_URI_MIN_LENGTH = 12;
// const PORTRAIT_URI_MAX_LENGTH = 256;
// const PASSWORD_MIN_LENGTH = 6;
// const PASSWORD_MAX_LENGTH = 20;

rongCloud.init(Config.RONGCLOUD_APP_KEY, Config.RONGCLOUD_APP_SECRET);

var router = express.Router();

/**
 * @api {post} /webim/user/login webim 登录接口
 * @apiName Login
 * @apiGroup User
 * @apiVersion 0.1.0
 *
 * @apiParam {String} uid  用户id, username
 * @apiParam {String} password  用户密码
 *
 * @apiSuccess {String} id 融云用户ID
 * @apiSuccess {String} rcToken 该用户的融云token
 * @apiSuccess {String} appKey 融云的appKey
 * @apiSuccess {String} authToken 用户的签名token
 * @apiSuccess {String} secretCode 用户免登陆进入电商url的加密code
 *
 * @apiSuccessExample 成功响应:
 *    HTTP/1.1
 *    {
 *     "code": 200,
 *       "result": {
 *         "id": "JLwaUloqv",
 *         "rcToken": "Sccg1H7h8qymwIYgEm9ayWvHCMGVI5hOYod++FnvBpoMeYYQFAvz2OM/YO87GI42iRno/ZMXIHCHCke8CMYTCQ==",
 *         "authToken": "8a32060431884399ba6aad847e2c1079",
 *         "secretCode": "$SHA$hSdOrrapa$qr_gwXwELrbfSZfe5JjxF-CYNCg",
 *         "appKey": "8w7jv4qb77uzy"
 *      }
 *    }
 */
router.post('/login', function (req, res, next) {
  let uid = req.body.uid;
  let password = req.body.password;
  logger.info(`用户 ${uid} 正在登录`);
  if (!uid || !password) {
    return res.status(400).send('用户名或密码错误');
  }

  co(function*() {
    let authInfo = yield auth.login(uid, password);
    // 查找并注册用户
    let user = yield UserService.findOrRegister(uid);
    Session.setAuthCookie(res, user.id);
    Session.setNicknameToCache(user.id, user.nickname);

    return res.send(new APIResult(200, Utility.encodeResults({
      id: user.id,
      rcToken: user.rongCloudToken,
      authToken: authInfo.token,
      secretCode: authInfo.secretCode,
      appKey: Config.RONGCLOUD_APP_KEY
    })));

  }).catch(err => {
    logger.warn(`用户 ${uid} 登录失败`, err);
    next(err);
  });
});

/**
 * @api {get} /webim/user/logout webim 登出接口
 * @apiName Logout
 * @apiGroup User
 * @apiVersion 0.1.0
 */
router.get('/logout', function (req, res) {
  res.clearCookie(Config.AUTH_COOKIE_NAME);
  return res.send(new APIResult(200));
});

/**
 * @api {get} /webim/user/get_token 获取融云token
 * @apiName GetToken
 * @apiGroup User
 * @apiVersion 0.1.0
 *
 * @apiSuccess {String} userId 融云用户ID
 * @apiSuccess {String} rcToken 该用户的融云token
 * @apiSuccess {String} appKey 融云的appKey
 *
 * @apiSuccessExample 成功响应:
 *    HTTP/1.1
 *    {
 *     "code": 200,
 *       "result": {
 *         "userId": "JLwaUloqv",
 *         "rcToken": "Sccg1H7h8qymwIYgEm9ayWvHCMGVI5hOYod++FnvBpoMeYYQFAvz2OM/YO87GI42iRno/ZMXIHCHCke8CMYTCQ==",
 *         "appKey": "8w7jv4qb77uzy"
 *      }
 *    }
 */
router.get('/get_token', function (req, res, next) {
  return User.findById(Session.getCurrentUserId(req, {
    attributes: ['id', 'nickname', 'portraitUri']
  })).then(function (user) {
    logger.info('用户', user.nickname, '正在查询token');
    return UserService.getAndUpdateToken(user.id, user.nickname, user.portraitUri).then(function (token) {
      return res.send(new APIResult(200, Utility.encodeResults({
        userId: user.id,
        rcToken: token,
        appKey: Config.RONGCLOUD_APP_KEY
      }, 'userId')));
    });
  }).catch(next);
});

/**
 * @api {get} /webim/user/online_status/batch 批量获取用户的在线状态
 * @apiName GetOnlineStatus
 * @apiGroup User
 * @apiVersion 0.1.0
 *
 * @apiParam {String[]} id 融云用户ID
 * @apiParam {Number} expires 过期时间，时间戳，如果在该时间戳之前，会重新从融云获取一次在线状态
 * 
 * @apiSuccess {Object[]} statues 在线状态列表
 *
 * @apiExample {bash} 示例：
 *      GET /webim/user/online_status/batch?id=JLwaUloqv&id=K69DpFSlN
 *
 * @apiSuccessExample 成功响应:
 *    HTTP/1.1
 *    {
 *      "code": 200,
 *      "result": [
 *        {
 *          "userId": "ZXEkcNQOm",
 *          "os": "Websocket",
 *          "timestamp": 1474508386265,
 *          "status": 0
 *        },
 *        {
 *          "userId": "7QqpXMtkB",
 *          "status": 1,
 *          "os": "",
 *          "timestamp": 1474508468435
 *        }
 *      ]
 *    }
 */
router.get('/online_status/batch', function (req, res, next) {
  var ids = req.query.id;
  if(!ids){
     return res.send(new APIResult(200, []));
  }

  if (!Array.isArray(ids)) {
    ids = [ids];
  }

  ids = Utility.decodeIds(ids);
  logger.info(`查询用户 ${ids} 的在线状态`);
  
  co(function*() {
    let statuses = yield UserService.findAndUpdateUsersOnlineStatus(ids, req.query.expires); 
    logger.info('从数据库获取在线状态为', statuses);
    // 加密id
    statuses = statuses.map(status => Object.assign({}, status, {userId: Utility.numberToString(status.userId)}));
    return res.send(new APIResult(200, statuses));
  }).catch(next);
});

/**
 * @api {get} /webim/user/batch 批量获取用户信息
 * @apiName GetUsers
 * @apiGroup User
 * @apiVersion 0.1.0
 *
 * @apiParam {String[]} id 融云用户ID
 *
 * @apiSuccess {Object[]} users 返回对应的用户列表
 *
 * @apiExample {bash} 示例：
 *      GET /webim/user/batch?id=JLwaUloqv&id=K69DpFSlN
 *
 * @apiSuccessExample 成功响应:
 *    HTTP/1.1 200 OK
 *    {
 *      "code": 200,
 *      "result": [
 *        {
 *          "id": "K69DpFSlN",
 *          "uid": "hlzyh",
 *          "nickname": "张燕华",
 *          "contactNumber": "18688780069",
 *          "storeName": "华砺汽配旗舰店",
 *          "storeId": "HL000001",
 *          "partyGroup": "张燕华",
 *          "portraitUri": ""
 *        },
 *        {
 *          "id": "JLwaUloqv",
 *          "uid": "eptjb",
 *          "nickname": "江滨",
 *          "contactNumber": "18688780069",
 *          "storeName": "欧配通官方旗舰店",
 *          "storeId": "OPT00001",
 *          "partyGroup": "江滨",
 *          "portraitUri": ""
 *        }
 *      ]
 *    }
 */
router.get('/batch', function (req, res, next) {
  var ids = req.query.id;
  if (!Array.isArray(ids)) {
    ids = [ids];
  }
  ids = Utility.decodeIds(ids);
  return User.findAll({
    where: {
      id: {
        $in: ids
      }
    },
    attributes: ['id', 'uid', 'nickname', 'contactNumber', 'storeName', 'storeId', 'partyGroup', 'portraitUri']
  }).then(function (users) {
    return res.send(new APIResult(200, Utility.encodeResults(users)));
  }).catch(next);
});

/**
 * @api {get} /webim/user/find 查找用户
 * @apiName GetUsers
 * @apiGroup User
 * @apiVersion 0.1.0
 *
 * @apiParam {String} kw 关键字（可以为uid,nickname,storeName）
 *
 * @apiSuccess {Object[]} users 返回对应的用户列表
 *
 * @apiExample {bash} 示例：
 *      GET /webim/user/find?kw=中鑫之宝深圳
 *
 * @apiSuccessExample 成功响应:
 *    HTTP/1.1 200 OK
 *     {
 *       "code": 200,
 *       "result": [
 *         {
 *           "id": "ZXEkcNQOm",
 *           "uid": "zxzbszd",
 *           "nickname": "中鑫之宝深圳店",
 *           "contactNumber": "18688780069",
 *           "storeName": "",
 *           "storeId": "",
 *           "partyGroup": "中鑫之宝深圳店",
 *           "portraitUri": ""
 *         },
 *         {
 *           "id": "7QqpXMtkB",
 *           "uid": "szdlzd",
 *           "nickname": "深圳店-李钟锭",
 *           "contactNumber": "18688780069",
 *           "storeName": "",
 *           "storeId": "",
 *           "partyGroup": "中鑫之宝深圳店",
 *           "portraitUri": ""
 *         }
 *       ]
 *     }
 */
router.get('/find', function (req, res, next) {
  let kw = req.query.kw;
  logger.info(`用户 ${Session.getCurrentUserId(req)} 正在查找用户 ${kw}`);
  let attributes = ['id', 'uid', 'nickname', 'contactNumber', 'storeName', 'storeId', 'partyGroup', 'portraitUri'];
  let users = [];

  co(function*() {
    if (!kw) {
      return users;
    }

    users = yield User.findAll({
      where: {
        uid: kw
      },
      attributes: attributes
    });

    if (!users.length) {
      users = yield User.findAll({
        where: {
          nickname: kw
        },
        attributes: attributes
      });
    }

    if (!users.length) {
      users = yield User.findAll({
        where: {
          $or: [
            {
              partyGroup: {$like: `%${kw}%`}
            },
            {
              storeName: {$like: `%${kw}%`}
            }
          ]
        },
        attributes: attributes
      });
    }
    return users;
  }).then(users => {
    res.send(new APIResult(200, Utility.encodeResults(users)));
  }).catch(function (err) {
    logger.warn('关键字查找用户失败', err);
    next(err);
  });
});

/**
 * @api {get} /webim/user/:id 指定用户信息
 * @apiName GetUser
 * @apiGroup User
 * @apiVersion 0.1.0
 *
 * @apiParam {String} id 用户在融云对应的id
 *
 * @apiSuccess {Object} user 返回用户信息
 *
 * @apiExample {bash} 示例：
 *      GET /webim/user/ZXEkcNQOm
 *
 * @apiSuccessExample 成功响应:
 *    HTTP/1.1 200 OK
 *    {
 *       "code": 200,
 *       "result": {
 *         "id": "7QqpXMtkB",
 *         "uid": "szdlzd",
 *         "nickname": "深圳店-李钟锭",
 *         "contactNumber": "18688780069",
 *         "storeName": "",
 *         "storeId": "",
 *         "partyGroup": "中鑫之宝深圳店",
 *         "portraitUri": ""
 *       }
 *     }
 */
router.get('/:id', function (req, res, next) {
  var userId;
  userId = req.params.id;
  userId = Utility.decodeIds(userId);
  return User.findById(userId, {
    attributes: ['id', 'uid', 'nickname', 'contactNumber', 'storeName', 'storeId', 'partyGroup', 'portraitUri']
  }).then(function (user) {
    if (!user) {
      return res.status(404).send('Unknown user.');
    }
    return res.send(new APIResult(200, Utility.encodeResults(user)));
  }).catch(next);
});

function checkUserOnline(userId) {
  return new Promise((resolve, reject) => {
    rongCloud.user.checkOnline(userId, function (err, result) {
      if (err) {
        return reject(err);
      }
      resolve(result);
    });
  });
}

module.exports = router;
